package com.xiaozhen.blog.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaozhen.blog.entity.Blog;
import com.xiaozhen.blog.entity.Tag;
import com.xiaozhen.blog.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * @create 2023-04-22 14:42
 */
@Controller
@RequestMapping("/tags")
public class TagController {
    @Autowired
    private TagService tagService;

    @GetMapping("/{id}")
    public String tags(@RequestParam(value = "page", required = false) Long page,
                       @PathVariable Long id,
                       Model model) {
        // 查询所有标签
        List<Tag> tagList = tagService.tagList();
        // 若传过来的 id 为 -1，那么默认选择第一个标签
        if (id == -1) {
            id = tagList.get(0).getId();
        }
        // 如果没有传入参数，那么我们把page定义为第 1 页
        if (page == null) {
            page = 1L;
        }
        // 创建对象，传递分页相关参数，每页记录数为 6
        Page<Blog> pageParam = new Page<>(page, 6);

        // 将数据返回给前端
        model.addAttribute("tags", tagList);
        model.addAttribute("activeTagId", id);
        model.addAttribute("page", tagService.blogPage(pageParam, id));
        return "tags";
    }
}
